package com.ux.iot.jetlinks.service.websocket;

import com.ux.iot.jetlinks.service.websocket.handler.JetlinksMessageListener;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;

import javax.websocket.*;
import java.util.List;
import java.util.function.Supplier;

/**
 * @author caixiaodao
 * @version 1.0
 * 功能描述
 * websocket 客户端
 * @date 2021/11/15 12:32
 */
@Slf4j
@ClientEndpoint
@AllArgsConstructor
@NoArgsConstructor
@Setter
@Getter
public class SingleWebsocketClientEndpoint {
    List<JetlinksConnectListener> listeners;
    JetlinksMessageListener jetlinksMessageListener;
    Supplier<Integer> closeEvent;
    @OnOpen
    public void open(Session session){
        log.info("websocke 已连接 通知监听器");
        SessionManager.addSession(session);
        listeners.forEach((item)->{
            item.connect(session);
            log.info("{}",item.getClass().getSimpleName());
        });
        // 启动心跳
        PingService.start();
    }
    @OnMessage
    public void onMessage(String message){
        //log.info("Server send message: " + message);
        jetlinksMessageListener.onMessage(message);
    }

    @OnClose
    public void onClose(){
        log.info("websocket 断开连接 通知监听器");
        listeners.forEach((item)->{
            log.info("{}",item.getClass().getSimpleName());
        });
        SessionManager.removeSingleSession();
        closeEvent.get();
        //停止发送心跳
        PingService.stop();
    }



}
